package com.alibaba.csp.sentinel.dashboard.controller.v2;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.alibaba.csp.sentinel.dashboard.repository.rule.RuleRepository;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisherV2;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author tom
 */
public class BasePublishController {

    private final Logger logger = LoggerFactory.getLogger(BasePublishController.class);

    protected Result<RuleEntity> publishRules(DynamicRulePublisherV2 publisher, RuleRepository repository, RuleEntity entity) throws Exception {
        List<RuleEntity> rules = repository.findAllByApp(entity.getApp());
        if (!publisher.publish(entity.getApp(), rules)) {
            logger.info("publish rule:{}, method:{}, fail: {}", entity.getClass().getName(), getInvokeMethodName(), JSON.toJSONString(rules));
            return Result.ofFail(500, "publish nacos failed!");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("publish rule:{}({}), method:{}", entity.getClass().getName(), JSON.toJSONString(rules), getInvokeMethodName());
        }
        return Result.ofSuccess(entity);
    }

    protected Result<Long> toIdResult(Result<RuleEntity> result) {
        if (result.isSuccess()) {
            return Result.ofSuccess(result.getData().getId());
        }
        return Result.ofFail(result.getCode(), result.getMsg());
    }

    private String getInvokeMethodName() {
        return Thread.currentThread().getStackTrace()[3].getMethodName();
    }
}
